package com.ruoyi.web.controller.module.customer;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.customer.domain.CustomerUser;
import com.ruoyi.customer.service.ICustomerUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/customer/user")
public class CustomerUserController extends BaseController
{
    @Autowired
    private ICustomerUserService userService;

    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('customer:user:list')")
    @PostMapping("/customerUserList")
    public TableDataInfo list(@RequestBody CustomerUser user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        startPageByPost();
        List<CustomerUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户邀请列表
     */
    @PostMapping("/customerUserInivteList")
    public TableDataInfo customerUserInivteList(@RequestBody CustomerUser user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        Long userId = SecurityUtils.getUserId();
        user.setInviteId(userId);
        startPageByPost();
        List<CustomerUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理 - 导出", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:export')")
    @PostMapping("/customerUserExport")
    public void export(HttpServletResponse response, CustomerUser user)
    {
        List<CustomerUser> list = userService.selectUserList(user);
        ExcelUtil<CustomerUser> util = new ExcelUtil<CustomerUser>(CustomerUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理 - 导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('customer:user:import')")
    @PostMapping("/customerUserImportData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<CustomerUser> util = new ExcelUtil<CustomerUser>(CustomerUser.class);
        List<CustomerUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/customerUserImportTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<CustomerUser> util = new ExcelUtil<CustomerUser>(CustomerUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('customer:user:query')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        if (StringUtils.isNotNull(userId))
        {
            CustomerUser customerUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, customerUser);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('customer:user:add')")
    @Log(title = "用户管理 - 新增", businessType = BusinessType.INSERT)
    @PostMapping("/customerUserAdd")
    public AjaxResult add(@Validated @RequestBody CustomerUser user, HttpServletRequest request)
    {
        String shopId = request.getHeader("ShopId"); // 店铺id
        if(shopId != null && !shopId.equals("")){
            user.setShopId(shopId);
        }
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "用户管理 - 修改", businessType = BusinessType.UPDATE)
    @PostMapping("customerUserUpdate")
    public AjaxResult edit(@Validated @RequestBody CustomerUser user)
    {
        userService.checkUserAllowed(user);
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('customer:user:remove')")
    @Log(title = "用户管理 - 删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('customer:user:resetPwd')")
    @Log(title = "用户管理-重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/customerUserResetPwd")
    public AjaxResult resetPwd(@RequestBody CustomerUser user)
    {
        return toAjax(userService.resetUserPwd(user.getUserId(), SecurityUtils.encryptPassword(user.getPassword())));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('customer:user:edit')")
    @Log(title = "用户管理-状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/customerUserChangeActive")
    public AjaxResult changeActive(@RequestBody CustomerUser user)
    {
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserActive(user));
    }
}
